﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;

namespace QuickExcel
{
    public partial class MinOrMaxVal : Form
    {
        Excel.Application App;

        public MinOrMaxVal()
        {
            InitializeComponent();            
        }

        private void MinOrMaxVal_Load(object sender, EventArgs e)
        {
            App = (Excel.Application)Globals.ThisAddIn.Application;
            txtRange.Text = App.Selection.Address;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrWhiteSpace(txtRange.Text))
            {
                MessageBox.Show("Please select a range");
                this.Activate();
                return;
            }
            
            bool bMaxVal = optMaxVal.Checked;
            bool bAllCells = optAllCells.Checked;
            Excel.Range rng = App.ActiveSheet.Range(txtRange.Text);
            object[,] oRng = rng.Value2;
            double dVal,dCurVal;
            string sAddress;
            string[] sCombineAdd;
            
            if (bMaxVal)            
                dVal = App.WorksheetFunction.Max(oRng);
            else
                dVal = App.WorksheetFunction.Min(oRng);

            sAddress = "";

            for (int i = 1; i <= oRng.GetLength(0); i++)
            {
                for (int j = 1; j <= oRng.GetLength(1); j++)
                {
                    if(!string.IsNullOrWhiteSpace(Convert.ToString(oRng[i,j])) && double.TryParse(Convert.ToString(oRng[i,j]), out dCurVal))
                    {
                        if (dVal == dCurVal)
                            sAddress += rng.Cells[i, j].Address + " ";
                    }
                }
            }

            sAddress = App.WorksheetFunction.Trim(sAddress);

            sAddress = sAddress.Replace(" ", ",").Replace("$", "");

            if ((new Regex(@",")).Matches(sAddress).Count > 0 || sAddress.Length > 0)
            {
                sCombineAdd = sAddress.Split(',');
                sAddress = sCombineAdd[0];

                foreach (string str in sCombineAdd)
                {
                    sAddress = App.Union(App.ActiveSheet.Range(sAddress), App.ActiveSheet.Range(str)).Address;
                }

                if (bAllCells)
                    App.ActiveSheet.Range(sAddress).Select();
                else
                    App.ActiveSheet.Range(sAddress).Cells[1,1].Select();
            }   

        }
    }
}
